package kr.hkit.androidcomplete03.ch20;

import kr.hkit.androidcomplete03.R;
import kr.hkit.androidcomplete03.ch20.FragmentTest.CounterFragment;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

public class FragmentManagerTest extends Activity {
	FragmentManager fm;
	
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.fragmentmanagertest);
		
		fm = getFragmentManager();
	}
	
	public void mOnClick(View v){	
		Fragment frag = fm.findFragmentById(R.id.frame);
		
		switch(v.getId()){
		case R.id.btnadd:
			if (frag == null){
				CounterFragment cf = new CounterFragment();
				fm.beginTransaction().add(R.id.frame, cf, "counter").commit();
			}else{
				Toast.makeText(this, "이미 추가되었음", Toast.LENGTH_LONG).show();
			}
			break;
		case R.id.btnremove:
			if (frag == null){
				Toast.makeText(this, "프래그먼트가 없음", Toast.LENGTH_LONG).show();
			}else{
				fm.beginTransaction().remove(frag).commit();
			}
			break;
		case R.id.btnreplace:
			if (frag == null){
				Toast.makeText(this, "프래그먼트가 없음", Toast.LENGTH_LONG).show();
			}else{
				if (frag.getTag().equalsIgnoreCase("counter")){
					TextFragment tf = new TextFragment();
					fm.beginTransaction().replace(R.id.frame, tf, "text").commit();
				}else{
					CounterFragment cf = new CounterFragment();
					fm.beginTransaction().replace(R.id.frame, cf, "counter").commit();
				}
			}
			break;
		case R.id.btnhideshow:
			if (frag == null) {
				Toast.makeText(this, "프래그먼트가 없습니다.", 0).show();
			} else {
				FragmentTransaction tr = fm.beginTransaction();
				if (frag.isHidden()) {
					tr.show(frag);
				} else {
					tr.hide(frag);
				}
				tr.commit();
			}
			break;
		}
	}
}
